<template>
  <view class="order-detail-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="nav-left" @click="goBack">
        <uni-icons type="left" size="20" color="#ffffff"></uni-icons>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="isLoading">
      <view class="loading-content">
        <text class="loading-text">正在加载订单详情...</text>
      </view>
    </view>
    
    <!-- 支付成功区域 -->
    <view class="success-section">
      <!-- 成功状态文字 -->
      <text class="success-text">支付成功</text>
      
      <!-- 返回首页按钮 -->
      <view class="return-btn" @click="goToHome">
        返回首页
      </view>
    </view>

    <!-- 订单详情卡片 -->
      <!-- 订单信息卡片 -->
      <view class="info-card">
        <view class="order-summary-header">
          <view class="summary-row">
            <text class="summary-label">实付</text>
            <text class="summary-value">¥{{ chargeOrderData ? chargeOrderData.orderRealPrice || '0.00' : '0.00' }}</text>
          </view>
          <view class="summary-row" @click="goToPreFeeDetail">
            <text class="summary-label">剩余</text>
            <text class="summary-value remaining-value">¥{{ chargeOrderData ? (chargeOrderData.advanceTotal - chargeOrderData.orderRealPrice).toFixed(2) : '0.00' }}</text>
            
          </view>
          <view class="card-footer">
            <text class="detail-link" @click="goToPreFeeDetail">已原路退回></text>
          </view>
        </view>
        <view class="card-content">
          <view class="info-row">
            <text class="info-label">订单总金额\n</text>
            <uni-icons type="help" size="16" color="#666" @click="showFeeCalculation"></uni-icons>
            <text class="info-value">¥{{ chargeOrderData ? chargeOrderData.orderRealPrice || '0.00' : '0.00' }}</text>
          </view>
          <view class="info-row">
            <text class="summary-label">优惠总金额</text>
            <text class="info-value discount">-¥{{ chargeOrderData ? chargeOrderData.discount || '0.00' : '0.00' }}</text>
          </view>
        </view>
        <view class="card-footer">
          <text class="detail-link" @click="goToFeeDetail">费用明细></text>
        </view>
      </view>

      <!-- 充电站卡片 -->
      <view class="info-card">
        <view class="card-content">
          <view class="info-row">
            <text class="summary-label">充电站</text>
            <text class="info-value">{{ chargeOrderData ? chargeOrderData.stationName || '未知' : '未知' }}</text>
          </view>
          <view class="info-row">
            <text class="summary-label">订单编号</text>
            <view class="info-value-with-action">
              <text class="info-value">{{ formatOrderNumber(chargeOrderData ? chargeOrderData.orderNumber : '') }}</text>
              <text class="action-btn" @click="copyOrderNumber">复制</text>
            </view>
          </view>
          <view class="info-row">
            <text class="summary-label">充电枪编号</text>
            <text class="info-value">{{ chargeOrderData && chargeOrderData.status ? chargeOrderData.status.connectorId || '未知' : '未知' }}</text>
          </view>
          <view class="info-row">
            <text class="summary-label">支付方式</text>
            <text class="info-value">{{ chargeOrderData ? getPaymentMethodText(chargeOrderData.payChannel) : '未知' }}</text>
          </view>
          <view class="info-row">
            <text class="summary-label">支付时间</text>
            <text class="info-value">{{ chargeOrderData ? formatDateTime(chargeOrderData.paySuccessTime) : '未知' }}</text>
          </view>
        </view>
      </view>

      <!-- 充电信息卡片 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">充电信息</text>
          <text class="charge-type">{{ formattedEquipmentType }}</text>
        </view>
        <view class="dividing-line"></view>
        <view class="card-content">
          <view class="timeline-section">
            <view class="timeline-header">
              <text class="energy-amount">{{ chargeOrderData ? chargeOrderData.totalPower + '度' : '0度' }}</text>
            </view>
            <view class="timeline-bar">
              <view class="timeline-start">
                <text class="date">{{ chargeOrderData ? formatDate(chargeOrderData.startTime) : '--' }}</text>
                <text class="time">{{ chargeOrderData ? formatTime(chargeOrderData.startTime) : '--' }} 起</text>
              </view>
              <view class="timeline-progress">
                <view class="progress-bar"></view>
                <view class="progress-arrow">▶</view>
              </view>
              <view class="timeline-end">
                <text class="date">{{ chargeOrderData ? formatDate(chargeOrderData.endTime) : '--' }}</text>
                <text class="time">止 {{ chargeOrderData ? formatTime(chargeOrderData.endTime) : '--' }}</text>
              </view>
            </view>
          </view>
          
          <!-- 费用明细 -->
          <view class="fee-details" v-if="chargeOrderData && chargeOrderData.status">
            <view class="fee-row">
              <text class="fee-label">电费</text>
              <text class="fee-value">¥{{ chargeOrderData.powerPrice || '0.00' }}</text>
            </view>
            <view class="fee-row">
              <text class="fee-label">服务费</text>
              <text class="fee-value">¥{{ chargeOrderData.servicePrice || '0.00' }}</text>
            </view>
            <view class="fee-row total-row">
              <text class="fee-label">总计</text>
              <text class="fee-value total-value">¥{{ chargeOrderData.orderRealPrice || '0.00' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 限时免费停车卡片 -->
      <view class="info-card">
        <view class="card-header">
          <view class="parking-header">
            <view class="parking-icon">
              <text class="parking-text">P</text>
            </view>
            <text class="card-title">限时免费停车</text>
          </view>
          <view class="license-plate">
            <text class="plate-text">{{ chargeOrderData ? chargeOrderData.carNumber : '沪A·AG6712' }}</text>
          </view>
        </view>
        <view class="card-content">
          <text class="parking-rules">绑定车牌号,充电,减免{{ chargeOrderData && chargeOrderData.freeParkTime ? chargeOrderData.freeParkTime : '暂无' }}小时,超时按{{ chargeOrderData && chargeOrderData.parkFee ? chargeOrderData.parkFee : '暂无' }}收费</text>
        </view>
      </view>
    
  </view>
</template>

<script>
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { chargingOrderDetails } from '@/api/charging/index.js'

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      orderId: null,
      orderNumber: '', // 订单编号，后续会从接口获取
      orderNum: '', // 订单号，从路由获取
      chargeOrderData: null, // 充电订单数据
      isLoading: false, // 加载状态
      from: null // 用于判断页面来源
    }
  },
  onLoad(options) {
    this.orderId = options.id;
    this.orderNum = options.orderNum; // 获取订单号
    this.from = options.from; // 获取页面来源
    console.log('订单ID:', this.orderId);
    console.log('订单号:', this.orderNum);
    console.log('页面来源:', this.from);
    
    // 如果有订单号，查询充电订单
    if (this.orderNum) {
      this.queryChargeOrderData();
    }
  },
  methods: {
    // 查询充电订单数据
    queryChargeOrderData() {
      if (!this.orderNum) {
        console.error('订单号不存在');
        return;
      }
      
      this.isLoading = true;
      console.log('查询充电订单，参数:', this.orderNum);
      chargingOrderDetails({ orderNum: this.orderNum }).then(res => {
        console.log('充电订单查询结果:', res);
        this.isLoading = false;
        
        if (res && res.code === 0 && res.success && res.data) {
          this.chargeOrderData = res.data;
          this.updateOrderDisplay();
        } else {
          console.error('充电订单查询失败:', res.msg);
          uni.showToast({
            title: res.msg || '获取订单详情失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('充电订单接口调用失败:', error);
        this.isLoading = false;
        uni.showToast({
          title: error.msg || '网络请求失败',
          icon: 'none'
        });
      });
    },
    
    // 更新订单显示
    updateOrderDisplay() {
      if (!this.chargeOrderData) return;
      
      // 更新订单编号
      if (this.chargeOrderData.orderNumber) {
        this.orderNumber = this.chargeOrderData.orderNumber;
      }
      
      console.log('订单数据已更新:', this.chargeOrderData);
    },
    
    goToHome() {
      uni.reLaunch({
        url: '/pages/index/index'
      });
    },
    
    // 返回处理 - 根据页面来源决定返回行为
    goBack() {
      // 通过URL参数判断来源，而不是通过页面栈
      if (this.from === 'stopCharging') {
        console.log('从停止充电页面进入，跳转到首页');
        uni.reLaunch({
          url: '/pages/index/index'
        });
      } else {
        console.log('正常返回上一页');
        // 正常返回上一页
        uni.navigateBack();
      }
    },
    
    goToPreFeeDetail() {
      if (!this.chargeOrderData) {
        uni.showToast({
          title: '订单数据不存在',
          icon: 'none'
        });
        return;
      }
      
      // 准备传递的预付费用数据
      const preFeeData = {
        orderNum: this.orderNum,
        orderNumber: this.chargeOrderData.orderNumber,
        advanceTotal: this.chargeOrderData.advanceTotal,
        orderRealPrice: this.chargeOrderData.orderRealPrice,
        chargeBalanceAdvance: this.chargeOrderData.chargeBalanceAdvance,
        cashAdvance: this.chargeOrderData.cashAdvance,
        payChannel: this.chargeOrderData.payChannel,
        startTime: this.chargeOrderData.startTime,
        stationName: this.chargeOrderData.stationName,
        carNumber: this.chargeOrderData.carNumber
      };
      
      // 将数据转换为查询字符串
      const queryString = Object.keys(preFeeData)
        .filter(key => preFeeData[key] !== null && preFeeData[key] !== undefined)
        .map(key => `${key}=${encodeURIComponent(preFeeData[key])}`)
        .join('&');
      
      uni.navigateTo({
        url: `/pages/preFeeDetail/preFeeDetail?${queryString}`
      });
    },
    formatOrderNumber(orderNumber) {
      if (orderNumber.length > 15) {
        return orderNumber.substring(0, 15) + '...';
      }
      return orderNumber;
    },
    showFeeCalculation() {
      uni.showModal({
        title: '费用计算方式',
        content: '充电账单以"元"为几张单位,元以下计至分,分以下四舍五入',
        showCancel: false,
        confirmText: '返回',
        confirmColor: '#fc7700'
      });
    },
    showPaymentMethod() {
      uni.showModal({
        title: '支付方式',
        content: '预付费: 微信支付',
        showCancel: false,
        confirmText: '知道了~',
        confirmColor: '#fc7700'
      });
    },
    goToFeeDetail() {
      if (!this.chargeOrderData) {
        uni.showToast({
          title: '订单数据不存在',
          icon: 'none'
        });
        return;
      }
      
      // 准备传递的数据
      const feeData = {
        orderNum: this.orderNum,
        orderNumber: this.chargeOrderData.orderNumber,
        orderRealPrice: this.chargeOrderData.orderRealPrice,
        totalPower: this.chargeOrderData.totalPower,
        startTime: this.chargeOrderData.startTime,
        endTime: this.chargeOrderData.endTime,
        stationName: this.chargeOrderData.stationName,
        carNumber: this.chargeOrderData.carNumber,
        payChannel: this.chargeOrderData.payChannel,
        // 直接从根级别获取这些字段
        powerPrice: this.chargeOrderData.powerPrice,
        servicePrice: this.chargeOrderData.servicePrice,
        discount: this.chargeOrderData.discount
      };
      
      // 如果有充电枪信息，也一并传递
      if (this.chargeOrderData.status) {
        feeData.connectorId = this.chargeOrderData.status.connectorId;
      }
      
      console.log('准备传递给费用明细页的数据:', feeData);
      
      // 将数据转换为查询字符串
      const queryString = Object.keys(feeData)
        .filter(key => feeData[key] !== null && feeData[key] !== undefined)
        .map(key => `${key}=${encodeURIComponent(feeData[key])}`)
        .join('&');
      
      console.log('费用明细页URL查询字符串:', queryString);
      
      uni.navigateTo({
        url: `/pages/feeDetail/feeDetail?${queryString}`
      });
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '--';
      const date = new Date(timestamp);
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${month}月${day}日`;
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '--';
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },

    // 格式化日期时间
    formatDateTime(timestamp) {
      if (!timestamp) return '--';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 复制订单编号
    copyOrderNumber() {
      const orderNumber = this.chargeOrderData ? this.chargeOrderData.orderNumber : '';
      if (!orderNumber) {
        uni.showToast({
          title: '订单编号不存在',
          icon: 'none'
        });
        return;
      }
      
      uni.setClipboardData({
        data: orderNumber,
        success: function () {
          uni.showToast({
            title: '订单编号已复制',
            icon: 'none'
          });
        },
        fail: function (error) {
          console.error('复制订单编号失败:', error);
          uni.showToast({
            title: '复制失败',
            icon: 'none'
          });
        }
      });
    },

    // 获取支付方式文本
    getPaymentMethodText(payChannel) {
      switch (payChannel) {
        case 'alipay':
          return '支付宝';
        case 'weichat':
          return '微信';
        case 'balance':
          return '混合支付';
        default:
          return '未知支付';
      }
    }
  },
  computed: {
    formattedEquipmentType() {
      if (!this.chargeOrderData || !this.chargeOrderData.equipmentInfo) {
        return '直流充电';
      }
      const equipmentType = this.chargeOrderData.equipmentInfo.equipmentType;
      switch (equipmentType) {
        case 1:
          return '直流设备';
        case 2:
          return '交流设备';
        case 3:
          return '交直流一体设备';
        case 4:
          return '无线设备';
        case 5:
          return '其他';
        default:
          return '直流充电';
      }
    }
  }
}
</script>

<style scoped>
.order-detail-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #fc7700 0%, #fc7700 30%, #f5f5f5 30%, #f5f5f5 100%);
  position: relative;
}

/* 状态栏占位 */
.status-bar {
  height: 7vh;
  width: 100%;
}

/* 自定义导航栏 */
.custom-navbar {
  position: fixed;
  top: 7vh;
  left: 0;
  width: 100%;
  height: 88rpx;
  background-color: transparent;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  z-index: 10;
}

.nav-left {
  width: 80rpx;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-content {
  background: #fff;
  padding: 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-text {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

/* 支付成功区域 */
.success-section {
  position: relative;
  height: 30vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

/* 成功图标 */
.success-icon {
  position: relative;
  z-index: 2;
  width: 120rpx;
  height: 120rpx;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.checkmark {
  color: #52c41a;
  font-size: 60rpx;
  font-weight: bold;
}

/* 成功状态文字 */
.success-text {
  position: relative;
  z-index: 2;
  font-size: 48rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 40rpx;
}

/* 返回首页按钮 */
.return-btn {
  position: relative;
  z-index: 2;
  background: #fc7700;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  padding: 20rpx 60rpx;
  border-radius: 50rpx;
  border: 2rpx solid #fff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

/* 订单详情卡片 */
.order-card {
  position: relative;
  margin: -50rpx 30rpx 0 30rpx;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  min-height: 400rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
  z-index: 3;
}

/* 确保卡片覆盖渐变背景的灰色部分 */
.order-card::before {
  content: '';
  position: absolute;
  top: -50rpx;
  left: 0;
  right: 0;
  height: 50rpx;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
}

/* 信息卡片样式 */
.info-card {
  background: #fff;
  border-radius: 16rpx;
  margin: 20rpx 30rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.charge-type {
  font-size: 24rpx;
  color: #666;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
}

.card-content {
  margin-bottom: 15rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #999;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  text-align: right;
  flex: 1;
  margin-left: 20rpx;
}

.info-value.discount {
  color: #fc7700;
}

.info-value-with-action {
  display: flex;
  align-items: center;
  flex: 1;
  margin-left: 20rpx;
}

.action-btn {
  font-size: 24rpx;
  color: #fc7700;
  margin-left: 20rpx;
  padding: 4rpx 12rpx;
  border: 1rpx solid #fc7700;
  border-radius: 8rpx;
  min-width: 50rpx;
}

.card-footer {
  text-align: right;
}

.detail-link {
  font-size: 24rpx;
  color: #999;
}

/* 订单摘要头部样式 */
.order-summary-header {
  margin-bottom: 20rpx;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.summary-row:last-child {
  justify-content: flex-end;
}

.summary-label {
  font-size: 28rpx;
  color: #666;
}

.summary-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}


.remaining-value {
  color: #fc7700; /* 剩余金额颜色 */
}

.summary-status {
  font-size: 24rpx;
}

/* 灰色分割线 */
.dividing-line {
  height: 1rpx;
  background: #f0f0f0;
  margin: 20rpx 0;
}

/* 充电信息时间轴样式 */
.timeline-section {
  padding: 20rpx 0;
}

.timeline-header {
  text-align: center;
  margin-bottom: 20rpx;
}

.energy-amount {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.timeline-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.timeline-start, .timeline-end {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.date {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.time {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.timeline-progress {
  flex: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin: 0 20rpx;
  overflow: visible;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background: #fc7700;
  border-radius: 4rpx;
  position: relative;
}

.progress-arrow {
  position: absolute;
  right: -15rpx;
  top: 22%;
  transform: translateY(-50%);
  color: #fc7700;
  font-size: 24rpx;
  font-weight: bold;
  z-index: 10;
}

.timeline-footer {
  text-align: center;
}

.duration {
  font-size: 28rpx;
  color: #666;
}

/* 费用明细样式 */
.fee-details {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.fee-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.fee-row:last-child {
  border-bottom: none;
}

.fee-label {
  font-size: 28rpx;
  color: #666;
}

.fee-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  text-align: right;
}

.total-row .fee-label {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.total-row .fee-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #fc7700;
}

/* 停车卡片样式 */
.parking-header {
  display: flex;
  align-items: center;
}

.parking-icon {
  width: 48rpx;
  height: 48rpx;
  background: #4a90e2;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15rpx;
}

.parking-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}

.license-plate {
  background: #52c41a;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
}

.plate-text {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.parking-rules {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}
</style> 